﻿using System;
using System.IO;
using System.Threading.Tasks;
using log4net;
using log4net.Config;
using log4net.Repository;
using Microsoft.AspNetCore.Authentication.Cookies;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.DataProtection;
using Microsoft.AspNetCore.Diagnostics;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Hosting.Internal;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Identity;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Razor;
using Microsoft.AspNetCore.Mvc.ViewEngines;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Options;
using Newtonsoft.Json.Converters;
using Newtonsoft.Json.Serialization;
using Von.Web.Framework;
using Von.Web.Models;

namespace Von.Web
{
    public class Startup
    {
        public Startup(IConfiguration configuration)
        {
            Configuration = configuration;
        }

        public IConfiguration Configuration { get; }

        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            services.Configure<CookiePolicyOptions>(options =>
            {
                options.CheckConsentNeeded = context => true;
                options.MinimumSameSitePolicy = SameSiteMode.None;
            });
            services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme)
                .AddCookie(CookieAuthenticationDefaults.AuthenticationScheme, options =>
                {
                    options.Cookie.Name = "_VonPortalCookie";
                    options.LoginPath = new PathString("/Account/Login");
                    options.LogoutPath = new PathString("/Account/LoginOut");
                    options.ExpireTimeSpan = TimeSpan.FromHours(4);//4小时后 Ticket过期
                });
            Runtime.serviceProvider = services.BuildServiceProvider();
            services.AddControllers()
            #region newtonsoft
            .AddNewtonsoftJson(options =>
            {
                //修改属性名称的序列化方式，首字母小写
                options.SerializerSettings.ContractResolver = new DefaultContractResolver();
                //修改时间的序列化方式
                options.SerializerSettings.Converters.Add(new IsoDateTimeConverter() { DateTimeFormat = "yyyy-MM-dd HH:mm:ss" });
            }
            );
            #endregion
            //services.AddControllersWithViews().AddNewtonsoftJson().;
            //用于寻找其他类库的页面
            services.Configure<RazorViewEngineOptions>(options =>
            {
                options.AreaViewLocationFormats.Clear();
                options.AreaViewLocationFormats.Add("/Views/{1}/{0}.cshtml");
                options.ViewLocationFormats.Add("/wwwroot/Skins/{0}" + RazorViewEngine.ViewExtension);
            });
            Runtime.mvcBuilder = services.AddMvc(options =>
            {
                options.EnableEndpointRouting = false;
            });
            services.AddControllersWithViews();
            //.SetCompatibilityVersion(CompatibilityVersion.Version_2_2).AddJsonOptions(options =>
            //{
            //    options.JsonSerializerOptions.PropertyNamingPolicy = null;  //json字符串大小写原样输出
            //    options.JsonSerializerOptions.IgnoreNullValues = true;      //json不输出null值
            //});
            //services.AddIdentity<IdentityUserInfo, IdentityRoleInfo>().AddRoleStore<IdentityRoleStore>().AddUserStore<IdentityUserStore>().AddDefaultTokenProviders();
            // Add application services.
            services.AddTransient<IEmailSender, MailSender>();
            services.AddSingleton<ICompositeViewEngine, CompositeViewEngine>();
            services.AddSession();
            //services.AddDataProtection().PersistKeysToFileSystem(new DirectoryInfo(@"\\Von-keys\"));
            Von.Web.Framework.Runtime.Load();
        }
        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IHostingEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }
            else
            {
                app.UseExceptionHandler("/Home/Error");
                // The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
                app.UseHsts();
            }
            app.UseHttpsRedirection();
            app.UseStaticFiles();
            //app.UseCookiePolicy();
            app.UseSession();

            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }
            else
            {
                app.UseExceptionHandler(builder => builder.Run(async context => await ErrorEvent(context)));
            }
            //Adds the authentication middleware to the pipeline
            app.UseAuthentication();
            app.UseMvc(routes =>
            {
                routes.Routes.Add(Von.Web.Route.VonRouteRuntime.Instance(routes.DefaultHandler)
                    .Add("IMGS", "/Service/Images/", Von.Web.Route.VonRouteRuntime.doImageService)
                    .Add("AJAX", "/Service/Execute/", Von.Web.Route.VonRouteRuntime.doAjaxService)
                    .Add("USERICON", "/Service/UserIcon/", Von.Web.Route.VonRouteRuntime.doUserIcon)
                    .Add("UPLOADED", "/Service/Uploaded/", Von.Web.Route.VonRouteRuntime.doUploadService));
                routes.MapRoute(
                    name: "area",
                    template: "{area:exists}/{controller}/{action}/{id?}");
                routes.MapRoute(
                    name: "default",
                    template: "{controller=Home}/{action=Index}/{id?}");
            });
            var requestLocalizationOptions = app.ApplicationServices.GetService<IOptions<RequestLocalizationOptions>>().Value;
            app.UseRequestLocalization(requestLocalizationOptions);
            Von.Web.Framework.Runtime.Init();
        }

        public async Task ErrorEvent(HttpContext context)
        {
            var feature = context.Features.Get<IExceptionHandlerFeature>();
            var error = feature?.Error;
            Runtime.Log.ErrorFormat("Error:{0},{1}", error.Message, error.StackTrace);
        }
    }
    public static class IdentityBuilderExtensions
    {
        /// <summary>
        /// Adds the default token providers used to generate tokens for reset passwords, change email
        /// and change telephone number operations, and for two factor authentication token generation.
        /// </summary>
        /// <param name="builder">The current <see cref="IdentityBuilder"/> instance.</param>
        /// <returns>The current <see cref="IdentityBuilder"/> instance.</returns>
        public static IdentityBuilder AddDefaultTokenProviders(this IdentityBuilder builder)
        {
            var userType = builder.UserType;
            var dataProtectionProviderType = typeof(DataProtectorTokenProvider<>).MakeGenericType(userType);
            var phoneNumberProviderType = typeof(PhoneNumberTokenProvider<>).MakeGenericType(userType);
            var emailTokenProviderType = typeof(EmailTokenProvider<>).MakeGenericType(userType);
            var authenticatorProviderType = typeof(AuthenticatorTokenProvider<>).MakeGenericType(userType);
            return builder.AddTokenProvider(TokenOptions.DefaultProvider, dataProtectionProviderType)
                .AddTokenProvider(TokenOptions.DefaultEmailProvider, emailTokenProviderType)
                .AddTokenProvider(TokenOptions.DefaultPhoneProvider, phoneNumberProviderType)
                .AddTokenProvider(TokenOptions.DefaultAuthenticatorProvider, authenticatorProviderType);
        }
    }
}
